import { ajaxCtx } from '@/api/config.js'
export default {
  data () {
    return {
      websocket: null,
      lockReconnect: false, // websokect 锁
      heartBeatTime: 5 * 60 * 1000, // 心跳检测时长
      timer: null // 定时变量
    }
  },
  beforeUnmount () {
    this.websocket && this.websocket.close()
  },
  methods: {
    /**
     * @desc 初始化websocket
     */
    initWebsocket () {
      if ('WebSocket' in window) {
        const wsUrl = `${location.protocol === 'http:' ? 'ws://' : 'wss://'}${ajaxCtx.ws}/api/lsbdbweb/socket/`
        console.log(wsUrl)
        this.websocket = new WebSocket(wsUrl)
        this.websocket.onopen = res => {
          console.log('WebSocket连接成功')
          this.resetHeart().startHeart()
        }
        this.websocket.onmessage = async res => {
          this.resetHeart().startHeart()
          try {
            const backData = JSON.parse(res.data)
            console.log('>>>>>>>>>> WebSocket backData：', backData)
            this.wsMsgHandler(backData)
          } catch (error) {
          }
          // {
          //    cameraIndexCode: "3cdc8460b3d945c68394743e878e1cec"
          // content: "性能测试点位 发送人脸抓拍事件"
          // eventName: "人脸抓拍事件"
          // happenTime: "2020-05-01T07:43:58.000+08:00"
          // latitude: "26.89819"
          // longitude: "112.60905"
          // picUrl:
          // }
        }
        this.websocket.onerror = () => {
          this.reconnectWs()
          // this.$message.error('WebSocket连接失败,请刷新当前页面!')
        }
        this.websocket.onclose = res => {
          this.reconnectWs()
        }
      } else {
        this.$message.warning('当前浏览器 Not support websocket')
      }
    },
    /**
     * @desc 重连机制
     */
    reconnectWs () {
      if (this.lockReconnect) return
      this.lockReconnect = true
      this.initWebsocket()
      // 没连接上会一直重连，设置延迟避免请求过多
      setTimeout(() => {
        this.lockReconnect = false
      }, 10000)
    },
    /**
     * @desc 重置定时
     */
    resetHeart () {
      // 重置定时
      clearTimeout(this.timer)
      return this
    },
    /**
     * @desc 开始Ws
     */
    startHeart () {
      // 开启定时
      this.timer = setTimeout(() => {
        // 心跳时间内收不到消息，主动触发连接关闭，开始重连
        this.websocket.send(JSON.stringify({ isExit: true }))
      }, this.heartBeatTime)
    }
  }
}
